package com.bmslz.monitorpre.job;

import com.bmslz.monitorpre.grpc.MonitorGrpcClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class PushDataJob {
    @Autowired
    private MonitorGrpcClient monitorGrpcClient;
    @Value("${client.project.domain}")
    private String domainsStr;

    /**
     * 测点数据推送demo
     * map中是监控模型的数据
     * 每一个key对应模型中的一个测点key,value为当前测点数据
     * Map<String, String> data = new HashMap<>();
     * data.put("cpu.use", "1");
     * data.put("mem.use", "100");
     * monitorGrpcClient.sendMetrics(data);
     * return "Metrics sent";
     */
    @Scheduled(fixedRateString = "#{${client.project.rate} * 1000}")
    public void executeTask() {
        //下面写你测点数据的获取逻辑:请求远程接口\获取本机信息\获取其他组件暴露的信息等方式都可以
        Map<String, String> map = getData();
        monitorGrpcClient.sendMetrics(map);
    }

    private Map<String, String> getData() {
        Map<String, String> map = new HashMap<>();
        String[] domainsArr = domainsStr.split(",");
        for (String domain : domainsArr) {
            log.info(domain);
            map.put(domain, String.valueOf(checkURLCertificate(domain)));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    public static long checkURLCertificate(String urlString) {
        HttpsURLConnection connection=null;
        try {
            URL url = new URL("https://" + urlString);
            connection = (HttpsURLConnection) url.openConnection();
            connection.connect();

            Certificate[] certificates = connection.getServerCertificates();

            if (certificates.length > 0 && certificates[0] instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate) certificates[0];
                return printCertificateInfo(cert);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(connection!=null){
                connection.disconnect();
            }
        }
        return -1;
    }

    private static long printCertificateInfo(X509Certificate cert) throws Exception {
        Date notAfter = cert.getNotAfter();
        Date currentDate = new Date();

        System.out.println("=== SSL证书信息 ===");
        System.out.println("主题: " + cert.getSubjectDN());
        System.out.println("颁发者: " + cert.getIssuerDN());
        System.out.println("序列号: " + cert.getSerialNumber());
        System.out.println("生效时间: " + cert.getNotBefore());
        System.out.println("过期时间: " + notAfter);
        System.out.println("签名算法: " + cert.getSigAlgName());

        long diff = notAfter.getTime() - currentDate.getTime();
        return diff / (24 * 60 * 60 * 1000);
    }

}

